<template>
  <DynamicDetailDialog
    v-model="visible"
    :title="title"
    :groups="detailGroups"
    :loading="loading"
    width="900px"
  >
    <template #share_url="{ value }">
      <div class="share-url-container">
        <el-link
          v-if="value"
          type="primary"
          :href="value"
          target="_blank"
          @click.stop
        >
          {{ value }}
        </el-link>
        <el-button
          v-if="value"
          size="small"
          type="primary"
          @click="copyToClipboard(value)"
          style="margin-left: 8px"
        >
          复制链接
        </el-button>
        <span v-else>-</span>
      </div>
    </template>

    <template #extract_code="{ value }">
      <div class="extract-code-container">
        <el-tag v-if="value" type="success" size="large">{{ value }}</el-tag>
        <el-button
          v-if="value"
          size="small"
          type="primary"
          @click="copyToClipboard(value)"
          style="margin-left: 8px"
        >
          复制
        </el-button>
        <span v-else>-</span>
      </div>
    </template>

    <template #file_list="{ value }">
      <div class="file-list-container" v-if="value && value.length > 0">
        <el-table :data="value" border size="small" max-height="300">
          <el-table-column prop="filename" label="文件名" min-width="200" />
          <el-table-column
            prop="size"
            label="大小"
            width="120"
            :formatter="formatFileSize"
          />
          <el-table-column
            prop="isdir"
            label="类型"
            width="80"
            :formatter="formatFileType"
          />
        </el-table>
      </div>
      <span v-else>-</span>
    </template>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button
        v-if="detailData?.share_url"
        type="primary"
        @click="openShareUrl"
      >
        打开分享链接
      </el-button>
    </template>
  </DynamicDetailDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import DynamicDetailDialog, {
  type DetailGroup,
} from "@/components/DynamicDetailDialog";
import { getResourceDetail } from "../../../servers";

interface Props {
  modelValue: boolean;
  resourceId?: string | null;
  resourceType?: "baidu" | "quark" | "xunleipan" | "aliyundrive" | null;
  keyword?: string | null;
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  resourceId: null,
  resourceType: null,
  keyword: null,
  title: "资源详情",
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "close"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
    if (!value) {
      emit("close");
    }
  },
});

const loading = ref(false);
const detailData = ref<any>(null);

// 监听弹窗打开，获取资源详情
watch(
  () => [visible.value, props.resourceId, props.resourceType, props.keyword],
  ([newVisible, newResourceId, newResourceType, newKeyword]) => {
    if (newVisible && newResourceId && newResourceType && newKeyword) {
      fetchResourceDetail(
        newResourceId as string,
        newResourceType as "baidu" | "quark" | "xunleipan",
        newKeyword as string
      );
    } else {
      detailData.value = null;
    }
  },
  { immediate: true }
);

// 获取资源详情
const fetchResourceDetail = async (
  resourceId: string,
  resourceType: "baidu" | "quark" | "xunleipan",
  keyword: string
) => {
  loading.value = true;
  try {
    const result = await getResourceDetail({
      resource_id: resourceId,
      resource_type: resourceType,
      keyword: keyword,
    });

    if (result.code === 200 || result.code === 2000) {
      detailData.value = result.data;
    } else {
      ElMessage.error(result.message || "获取资源详情失败");
      detailData.value = null;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资源详情失败");
    detailData.value = null;
  } finally {
    loading.value = false;
  }
};

// 格式化文件大小
const formatFileSize = (row: any) => {
  if (!row.size) return "未知";
  const size = typeof row.size === "string" ? parseInt(row.size) : row.size;
  if (size < 1024) return `${size}B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`;
  if (size < 1024 * 1024 * 1024)
    return `${(size / (1024 * 1024)).toFixed(1)}MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(1)}GB`;
};

// 格式化文件类型
const formatFileType = (row: any) => {
  return row.isdir === 1 || row.isdir === "1" ? "文件夹" : "文件";
};

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success("已复制到剪贴板");
  } catch (error) {
    // 降级方案
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand("copy");
      ElMessage.success("已复制到剪贴板");
    } catch (err) {
      ElMessage.error("复制失败");
    }
    document.body.removeChild(textarea);
  }
};

// 打开分享链接
const openShareUrl = () => {
  if (detailData.value?.share_url) {
    window.open(detailData.value.share_url, "_blank");
  }
};

// 详情分组数据
const detailGroups = computed<DetailGroup[]>(() => {
  if (!detailData.value || Object.keys(detailData.value).length === 0) {
    return [];
  }

  const data = detailData.value;

  return [
    {
      title: "基本信息",
      type: "normal",
      column: 2,
      border: true,
      items: [
        {
          key: "filename",
          label: "文件名称",
          value: data.filename || "-",
          span: 2,
        },
        {
          key: "resource_id",
          label: "资源ID",
          value: data.resource_id || "-",
        },
        {
          key: "resource_type",
          label: "资源类型",
          value:
            data.resource_type === "baidu"
              ? "百度网盘"
              : data.resource_type === "quark"
              ? "夸克网盘"
              : data.resource_type === "xunleipan"
              ? "迅雷网盘"
              : data.resource_type === "aliyundrive"
              ? "阿里云盘"
              : data.resource_type || "-",
          type: "tag",
          tagType: "info",
        },
        {
          key: "size",
          label: "文件大小",
          value: data.size ? formatFileSize({ size: data.size }) : "-",
        },
      ],
    },
    {
      title: "分享信息",
      type: "normal",
      column: 2,
      border: true,
      items: [
        {
          key: "share_url",
          label: "分享链接",
          value: data.share_url || "-",
          type: "custom",
          slot: "share_url",
          span: 2,
        },
        {
          key: "extract_code",
          label: "提取码",
          value: data.extract_code || "-",
          type: "custom",
          slot: "extract_code",
        },
      ],
    },
    {
      title: "文件列表",
      type: "normal",
      column: 1,
      border: true,
      items: [
        {
          key: "file_list",
          label: "文件列表",
          value: data.file_list || [],
          type: "custom",
          slot: "file_list",
          span: 1,
        },
      ],
    },
  ];
});

const handleClose = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.share-url-container,
.extract-code-container {
  display: flex;
  align-items: center;
}

.file-list-container {
  max-height: 300px;
  overflow-y: auto;
}
</style>
